/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.veditor.view.image;

import javax.swing.text.Element;
import javax.swing.tree.DefaultMutableTreeNode;
import offset.nodes.client.model.HierarchyTree;
import offset.nodes.client.model.NodeTypes;
import offset.nodes.client.model.PanelContainer;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.virtual.model.jcr.QName;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeDefinition;
import offset.nodes.client.view.SchemaNodeRenderer;
import offset.nodes.client.view.TreeNodeChooserDialog;
import offset.nodes.client.editor.Editor;
import offset.nodes.client.editor.model.DocumentContext;
import offset.nodes.client.veditor.model.VirtualImageModel;

/**
 *
 * @author Walter Lütgenau
 */
public class DataImagePanel extends javax.swing.JPanel {
    String nodeTypeName;
    NodeTypes types;
    SimpleNamespaceRegistry namespaces = SimpleNamespaceRegistry.getInstance();
    PanelContainer container;


    /** Creates new form DataIconPanel */
    public DataImagePanel() {
        initComponents();
    }

    public void init(Editor editor, PanelContainer container) {
        this.container = container;
        this.nodeTypeName = getParentNodeType(editor);
        this.types = (NodeTypes) editor.getProperties().get(Editor.PROP_NODE_TYPES);
    }

    public String getPropertyName() {
        return propertyTextField.getText();
    }

    protected String getParentNodeType(Editor editor) {
        VirtualImageModel model = new VirtualImageModel(new DocumentContext(editor.getBrowserPane()), editor);

        int pos = editor.getBrowserPane().getSelectionStart();
        Element e = model.getDocument().getParagraphElement(pos); // p-implied
        if (e != null && e.getElementCount() > 0)
            e = e.getElement(0); // content

        return model.getParentNodeType(e);
    }

    protected String getType(String path) {
        int index = path.lastIndexOf("/");
        if (index >= 0)
            path = path.substring(index + 1);
        return path.replaceAll("\\[.*\\]", "");
    }

    protected void enableOkButton() {
        if (propertyTextField.getText() != null)
            container.enableOkButton(true);
        else
            container.enableOkButton(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        propertyLabel = new javax.swing.JLabel();
        propertyTextField = new javax.swing.JTextField();
        propertyButton = new javax.swing.JButton();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle"); // NOI18N
        propertyLabel.setText(bundle.getString("Image.Data.property")); // NOI18N

        propertyButton.setText("...");
        propertyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectProperty(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(propertyLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(propertyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(propertyButton)
                .addContainerGap(39, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(66, 66, 66)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(propertyLabel)
                    .addComponent(propertyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(propertyButton))
                .addContainerGap(211, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void selectProperty(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectProperty
        QName typeName = QName.valueOf(namespaces.toQNameString(getType(nodeTypeName)));
        DefaultMutableTreeNode querySchemaNode = HierarchyTree.setupHierarchicalTree(QName.ANY_NAME,
                (NodeTypeDefinition) types.get(typeName), null, types, true, true);
        TreeNodeChooserDialog chooser = new TreeNodeChooserDialog(null, true, querySchemaNode);
        chooser.setCellRenderer(new SchemaNodeRenderer());
        chooser.setVisible(true);
        if (chooser.getReturnStatus() == TreeNodeChooserDialog.RET_OK) {
            DefaultMutableTreeNode selected = chooser.getSelectedNode();
            propertyTextField.setText(selected.toString());
            enableOkButton();
        }

    }//GEN-LAST:event_selectProperty
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton propertyButton;
    private javax.swing.JLabel propertyLabel;
    private javax.swing.JTextField propertyTextField;
    // End of variables declaration//GEN-END:variables
}
